package com.example.webserver.service.impl;

import com.example.webserver.entity.User;
import com.example.webserver.exception.ServiceException;
import com.example.webserver.mapper.Usermapper;
import com.example.webserver.service.IUserservice;
import com.example.webserver.utils.JWTUtil;
import com.example.webserver.utils.Md5Util;
import com.example.webserver.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class Userserviceimpl implements IUserservice {
    @Autowired
    Usermapper usermapper;
    @Override
    public String login(String username, String password) {
        User user=usermapper.findUserbyName(username);
        if(user==null){
            throw new ServiceException("输入错误");
        }
        if(!Md5Util.checkPassword(password,user.getPassword())){
            throw new ServiceException("密码错误");
        }
        Map<String,Object>claims=new HashMap<>();
        claims.put("id",user.getId());
        claims.put("username",user.getUsername());
        return JWTUtil.genToken(claims);
    }

    @Override
    public void register(String username,String password) {
       User rs=usermapper.findUserbyName(username);
       if(rs!=null){
           throw new ServiceException("用户名被占用");
       }
       String pass= Md5Util.getMD5String(password);

       User user=new User();
       user.setPassword(pass);
       user.setUsername(username);
       int row=usermapper.insert(user);
       if(row!=1){
           throw new ServiceException("插入数据时出现错误");
       }
    }

    @Override
    public void update(User user) {
        usermapper.update(user);
    }

    @Override
    public void updateAvatar(String Avatarurl) {
        Map<String,Object>map= ThreadLocalUtil.get();
        int id= (int) map.get("id");
        usermapper.updateAvatar(Avatarurl,id);
    }

    @Override
    public User getuserInfo() {
        Map<String,Object>map= ThreadLocalUtil.get();
        String username= (String) map.get("username");
        User user1=usermapper.findUserbyName(username);
        return user1;
    }

    @Override
    public void updatePsw(String password,String newPsw) {
        Map<String,Object>map= ThreadLocalUtil.get();
        String username= (String) map.get("username");
        User user=usermapper.findUserbyName(username);
        if(!Md5Util.checkPassword(password,user.getPassword())){
            throw new ServiceException("原密码错误");
        }
        String pass=Md5Util.getMD5String(newPsw);
        usermapper.updatePsw(pass,user.getId());
    }
}
